import { message, Form, Input, Row, Col } from 'antd'
import React, { useRef, useImperativeHandle, useState } from 'react'
import './index.less'
import ConfigEditTable from '../config-edit-table'
import {
  LoadingOutlined,
  PlusOutlined
} from '@ant-design/icons'
import IconSelect from '@/components/icon-select/index.jsx'

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

export const ConfigForm = React.forwardRef((props, ref) => {
  const { config, value, tableCom } = props
  const EditTableCom = tableCom || ConfigEditTable
  const [form] = Form.useForm()

  const formRef = useRef(null)

  const formProps = {
    initialValues: value,
    style: {
      height: '600px'
    }
  }

  // 方法暴露
  useImperativeHandle(
    ref,
    () => ({
      validateFields() {
        return formRef.current.validateFields()
      },
    }),
    []
  )

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传
      </div>
    </div>
  );

  const tableProps = {
    scroll: {y: 360}
  }
  
  return (
    <Form
      name="config-form"
      ref={ formRef }
      form={form}
      { ...formProps }
    >
      <Row gutter={12}>
        <Col span={12}>
          <Form.Item label={config.template} name="templateName">
            <Input placeholder='请输入' autoComplete='off'/>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="编码" name="templateCode">
            <Input placeholder='请输入'autoComplete='off'/>
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={12}>
        <Col span={12}>
          <Form.Item label="图标选择" name="icon">
            <IconSelect/>
          </Form.Item>
        </Col>
      </Row>
      
      <Form.Item label="" name="list">
        <EditTableCom tableProps={tableProps} />
      </Form.Item>
    </Form>
  )
})

ConfigForm.displayName = 'ConfigForm'

export default ConfigForm